<template>
  <div class='container'>
   <el-dialog :title="`${data.id?'修改':'新增'}目录`" :visible.sync="show" width="400px">
      <el-form ref="form" :model="formData" :rules="formRules" label-width="80px">
        <el-form-item
          v-if="!$route.query.id"
          label="所属学科"
          prop="subjectID"
          >
          <el-select v-model="formData.subjectID" style="width:100%">
            <el-option
            v-for="item in subjectOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="目录名称" prop="directoryName">
          <el-input v-model="formData.directoryName" placeholder="请输入目录名称"></el-input>
        </el-form-item>

      </el-form>
      <template #footer>
        <div style="text-align: right;">
          <el-button @click="show=false">取 消</el-button>
          <el-button @click="submit()" type="primary">确 定</el-button>
       </div>
      </template>
   </el-dialog>
  </div>
</template>

<script>
import { simple as subjectList } from '@/api/hmmm/subjects.js'
import { add, update } from '@/api/hmmm/directorys.js'

export default {
  name: 'DirectorysAdd',
  // 接收的数据
  props: {
    data: {
      required: true
    }
  },
  data () {
    return {
      show: false, // 对话框默认不显示
      formData: { // 表单数据
        id: null,
        subjectID: null,
        directoryName: null
      },
      // 表单校验规则
      formRules: {
        subjectID: [
          { type: 'number', message: '请选择所属学科', trigger: 'blur' }
        ],
        directoryName: [
          { required: true, message: '请输入目录名称', trigger: 'blur' }
        ]
      },
      // 下拉框的学科列表
      subjectOptions: []
    }
  },
  async created () {
    // 获取下拉框学科列表数据
    const res = await subjectList()
    console.log('学科列表', res)
    this.subjectOptions = res.data
  },
  methods: {
    // 点击打开对话框
    open () {
      this.show = true
      if (this.data.id) {
        // 从学科分类来打开的
        const { id, subjectID, directoryName } = this.data
        this.formData = { id, subjectID, directoryName }
      } else {
        // 本地打开的(新增/修改)
        this.formData = {
          id: null,
          subjectID: +this.$route.query.id || null,
          directoryName: null
        }
      }
      // 清除校验效果
      this.$nextTick(() => {
        this.$refs.form.clearValidate()// 清除表格每一项数据
      })
    },
    // 点击确定
    async submit () {
      this.$refs.form.validate(async valid => {
        if (valid) {
          if (!this.data.id) {
            // 新增目录
            await add(this.formData)
          } else {
            // 修改目录
            this.formData.id = this.data.id
            await update(this.formData)
          }
          this.$message.success('操作成功')
          this.show = false // 关对话框
          this.$emit('updateList') // 传父，更新目录列表
        }
      })
    }
  }
}
</script>

<style scoped lang='scss'></style>
